package com.example.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.article.dao.ArticleConfigDao;
import com.example.article.dao.ArticleHomeDao;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.article.service.ArticleHomeService;
import com.usian.model.article.dtos.ApArticleDto;
import com.usian.model.article.dtos.ArticleHomeDto;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.common.dtos.ResponseResult;

import com.usian.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.List;


@Service
@Slf4j
public class ArticleHomeServiceImpl implements ArticleHomeService {

    @Autowired
    private ArticleHomeDao articleHomeDao;
    @Autowired
    private ArticleConfigDao articleConfigDao;

    @Override
    public ResponseResult load(ArticleHomeDto articleHomeDto) {
        LambdaQueryWrapper<ApArticle> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (articleHomeDto.getChannelId() != null) {
            lambdaQueryWrapper.eq(ApArticle::getChannelId, articleHomeDto.getChannelId());
        }
        if (articleHomeDto.getFlag() != null) {
            lambdaQueryWrapper.eq(ApArticle::getFlag, articleHomeDto.getFlag());
        }
        Page<ApArticle> apArticlePage = new Page<>(1, 10);
        lambdaQueryWrapper.orderByDesc(ApArticle::getPublishTime);
        switch (articleHomeDto.getType()) {
            case "1":
                lambdaQueryWrapper.ge(ApArticle::getPublishTime, articleHomeDto.getMaxBehotTime());
                break;
            case "2":
                lambdaQueryWrapper.le(ApArticle::getPublishTime, articleHomeDto.getMinBehotTime());
                break;
            default:
                break;
        }

        IPage<ApArticle> apArticleIPage = articleHomeDao.selectPage(apArticlePage, lambdaQueryWrapper);
        List<ApArticle> articleList = apArticleIPage.getRecords();
        return ResponseResult.okResult(articleList);
    }
    
    @Override
    public ResponseResult getArticleDetail(Long id) {
        //查询文章配置表，文章是否删除或不存在
        LambdaQueryWrapper<ApArticleConfig> queryWrapper = new LambdaQueryWrapper<ApArticleConfig>();
        queryWrapper.eq(ApArticleConfig::getArticleId,id);
        ApArticleConfig apArticleConfig = articleConfigDao.selectOne(queryWrapper);
        //文章存在
        if (!apArticleConfig.getIsDown()&&!apArticleConfig.getIsDelete()){
            ApArticle apArticle = articleHomeDao.selectById(id);
            return ResponseResult.okResult(apArticle);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
}
